package com.ag.improvedjava.iterable;

import java.util.Iterator;
import java.util.NoSuchElementException;

import com.ag.improvedjava.exceptions.OverflowException;

final class RangeIterable implements Iterable<Integer> {

	public Integer start;
	public Integer count;
	
	RangeIterable(Integer start, Integer count) {
		this.start = start;
		this.count = count;
	}


	@Override
	public Iterator<Integer> iterator() {
		return new RangeIterator(start, count);
	}

}

class RangeIterator extends UnmodifiableIterator<Integer> {

	private Integer start;
	private Integer count;
	private Integer localCount;

	RangeIterator(Integer start, Integer count) {
		this.start = start;
		this.count = count;
		this.localCount = 0;
	}

	@Override
	public boolean hasNext() {
		return localCount < count;
	}

	@Override
	public Integer next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}
		if (start + localCount == Integer.MIN_VALUE) {
			throw new OverflowException("Values for the range are greater than Integer.MAX_VALUE");
		}
		return start + localCount++;
	}

}